package com.ruoyi.web.controller.shop.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.SysConfigConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.entity.VO.CouponSearchVO;
import com.ruoyi.common.entity.VO.CouponVO;
import com.ruoyi.common.entity.VO.member.MemberCouponVO;
import com.ruoyi.common.entity.VO.member.MemberGetCouponVO;
import com.ruoyi.common.entity.VO.product.PetrolProductVO;
import com.ruoyi.common.entity.VO.shop.ShopProductSearchVO;
import com.ruoyi.common.entity.VO.shop.ShopProductVO;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.exception.BusinessException;
import com.ruoyi.common.utils.ShiroUtils;
import com.ruoyi.framework.manager.AsyncManager;
import com.ruoyi.framework.manager.factory.AsyncFactory;
import com.ruoyi.web.controller.shop.mapper.IBackShopProductCouponLinkMapper;
import com.ruoyi.web.controller.shop.service.IBackShopCouponService;
import com.ruoyi.web.controller.shop.service.IBackShopProductService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * 站点-优惠券管理
 */
@Controller
@RequestMapping("/back/shopCoupon")
public class BackShopCouponController extends BaseController {
    private String prefix = "shop/coupon";

    @Resource
    private IBackShopCouponService shopCouponService;

    @Resource
    private IBackShopProductService shopProductService;

    @Resource
    private IBackShopProductCouponLinkMapper backShopProductCouponLinkMapper;


    /**
     * 页面-站点优惠券列表
     *
     * @return
     */
    @RequiresPermissions("back:shopCoupon:list")
    @GetMapping
    public String list(ModelMap mmap) {
        AsyncManager.me().execute(AsyncFactory.refreshCoupon(""));
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        List<ShopProductVO> petrolList = shopProductService.searchList(searchVO);
        mmap.put("petrolList",petrolList);
        return prefix + "/list";
    }

    /**
     * 页面-站点优惠券列表
     *
     * @return
     */
    @RequiresPermissions("back:shopCoupon:getList")
    @GetMapping("/getList/{couponId}")
    public String getList(@PathVariable("couponId") Long couponId,ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        mmap.put("couponId",couponId);
        return prefix + "/getList";
    }

    /**
     * 数据查询-店铺优惠券列表（搜索）
     *
     * @param searchVO
     * @return
     */
    @RequiresPermissions("back:shopCoupon:list")
    @PostMapping("/searchList")
    @ResponseBody
    public TableDataInfo searchList(CouponSearchVO searchVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        searchVO.setShopId(ShiroUtils.getShopId());
        startPage();
        List<CouponVO> list = shopCouponService.searchList(searchVO);
        return getDataTable(list);
    }

    /**
     * 数据查询-会员优惠券列表（搜索）
     *
     * @param searchVO
     * @return
     */
    @RequiresPermissions("back:shopCoupon:getList")
    @PostMapping("/searchGetList")
    @ResponseBody
    public TableDataInfo searchGetList(CouponSearchVO searchVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        searchVO.setShopId(ShiroUtils.getShopId());
        startPage();
        List<MemberCouponVO> list = shopCouponService.searchMemberList(searchVO);
        return getDataTable(list);
    }

    /**
     * 页面-新增店铺优惠券
     *
     * @return
     */
    @RequiresPermissions("back:shopCoupon:add")
    @GetMapping("/add")
    public String add(ModelMap mmap) {
        if (0 == ShiroUtils.getShopId()) {
            return "redirect:/back/shop/switchShop";
        }
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        List<ShopProductVO> petrolList = shopProductService.searchList(searchVO);
        petrolList.forEach(x->x.setSelected(true));
        mmap.put("petrolList",petrolList);
        return prefix + "/add";
    }

    /**
     * 页面-选择需要赠送的会员
     *
     * @return
     */
    @RequiresPermissions("back:shopCoupon:sendToMember")
    @GetMapping("/selectMember/{couponIdStr}")
    public String selectMember(@PathVariable("couponIdStr") String couponIdStr, ModelMap mmap) {
        mmap.put("couponIdStr",couponIdStr);
        return prefix + "/selectMember";
    }

    /**
     * 页面-编辑店铺优惠券
     *
     * @param couponId 优惠券ID
     * @return
     */
    @RequiresPermissions("back:shopCoupon:edit")
    @GetMapping("/edit/{couponId}")
    public String edit(@PathVariable("couponId") Long couponId, ModelMap mmap) {
        ShopProductSearchVO searchVO = new ShopProductSearchVO();
        searchVO.setShopId(ShiroUtils.getShopId());
        searchVO.setSystemModule(SysConfigConstants.SystemModuleEnum.PETROL.getValue());
        searchVO.setIsEnable(1);
        searchVO.setIsDelete(0);
        List<ShopProductVO> petrolList = shopProductService.searchList(searchVO);
        if (petrolList.size() > 0) {
            List<Long> productIdArr = backShopProductCouponLinkMapper.searchIdListByCouponId(searchVO.getShopId(), couponId);
            for (ShopProductVO one:petrolList){
                for(Long productId:productIdArr){
                    if(one.getId().equals(productId)){
                        one.setSelected(true);
                        break;
                    }
                }
            }
        }
        mmap.put("petrolList", petrolList);
        mmap.put("couponInfo", shopCouponService.getInfoById(couponId));
        return prefix + "/edit";
    }

    /**
     * 数据操作-批量赠送优惠券
     *
     * @param memberGetCouponVO
     * @return
     */
    @Log(title = "站点-店铺优惠券赠送", businessType = BusinessType.INSERT)
    @RequiresPermissions("back:shopCoupon:sendToMember")
    @PostMapping("/sendToMember")
    @ResponseBody
    public AjaxResult sendToMember(MemberGetCouponVO memberGetCouponVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        memberGetCouponVO.setShopId(ShiroUtils.getShopId());
        memberGetCouponVO.setCreateBy(ShiroUtils.getSysUser().getUserName());
        shopCouponService.sendToMember(memberGetCouponVO);
        return success("赠送成功");
    }

    /**
     * 数据新增-添加店铺优惠券
     *
     * @param couponVO
     * @return
     */
    @Log(title = "总后台-店铺优惠券管理", businessType = BusinessType.INSERT)
    @RequiresPermissions("back:shopCoupon:add")
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult add(CouponVO couponVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        couponVO.setShopId(ShiroUtils.getShopId());
        if (Constants.FAIL.equals(shopCouponService.checkCouponTitleUnique(couponVO))) {
            return error("新增优惠券'" + couponVO.getTitle() + "'失败，优惠券已存在");
        }
        couponVO.setCreateBy(ShiroUtils.getSysUser().getLoginName());
        return toAjax(shopCouponService.insertCoupon(couponVO));
    }

    /**
     * 数据更新-编辑店铺优惠券信息
     *
     * @param couponVO 店铺优惠券信息
     * @return
     */
    @Log(title = "总后台-店铺优惠券管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions(value = {"back:shopCoupon:edit", "back:shopCoupon:editMyself"}, logical = Logical.OR)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(CouponVO couponVO) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        couponVO.setShopId(ShiroUtils.getShopId());
        if (Constants.FAIL.equals(shopCouponService.checkCouponTitleUnique(couponVO))) {
            return error("修改优惠券'" + couponVO.getTitle() + "'失败，优惠券已存在不允许覆盖！");
        }
        couponVO.setUpdateBy(ShiroUtils.getSysUser().getLoginName());
        return AjaxResult.success(shopCouponService.updateCoupon(couponVO));
    }

    /**
     * 数据更新-删除店铺优惠券
     *
     * @param ids
     * @return
     */
    @Log(title = "总后台-店铺优惠券管理", businessType = BusinessType.DELETE)
    @RequiresPermissions("back:shopCoupon:remove")
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult delete(String ids) {
        if (0 == ShiroUtils.getShopId()) {
            throw new BusinessException("请先切换站点！");
        }
        Long couponId = Long.valueOf(ids);
        return toAjax(shopCouponService.deleteCouponById(ShiroUtils.getShopId(),couponId));
    }
}
